import { pathToFileURL } from "url"
import { h } from "koishi"
import * as repeater from "koishi-plugin-repeater"

export const name = "repeater-wrap"

export function apply(ctx) {
  ctx.plugin(repeater, {
    onRepeat: ({ repeated, times, users, content }, session) => {
      const elements = h.parse(content)

      // 不复读接龙表情或其他较新的 QQ 表情
      if (
        elements.length === 1 &&
        elements[0].type === "face" &&
        (!elements[0].platform || elements[0].platform === "onebot") &&
        (
          elements[0].id >= 392 && elements[0].id <= 394 ||
          elements[0].id >= 415
        )
      ) return

      const userCount = Object.keys(users).length + +!!repeated
      const rand = Math.random()
      ctx.logger.debug({ repeated, times, userCount, rand, users, userId: session.userId })
      if (!repeated && users[session.userId] <= 1 && rand < (4 * userCount - 7) / userCount**2) {
        return content
      } else if (rand >= 20 / (times + 12)) {
        return h.image(pathToFileURL("assets/noplusone.jpg").href)
      }
    },
  })
}
